import Vue from "vue";
import Vuex from "vuex";
import VuexPersistence from "vuex-persist";
//要设置的全局访问的state对象
// 配置数据存储到哪里
const vuexLocal = new VuexPersistence({
  storage: window.sessionStorage,
  reducer: state => ({
    token: state.token,
    user: state.user
  })
});
Vue.use(Vuex);
const state = {
  token: null,
  menu: null,
  user: {
    username: "游客900_"
  },
  level: null,
  roleId: ""
};

const getters = {
  get_roleId() {
    var roleId = window.sessionStorage["roleId"];
    if (roleId) {
      state.roleId = JSON.parse("roleId");
    }
  },
  get_token() {
    var token = window.sessionStorage["token"];
    if (token) {
      state.token = JSON.parse(token);
    }
    return state.token;
  },
  get_user() {
    var user = window.sessionStorage["user"];
    if (user) {
      state.user = JSON.parse(user);
    }
    if (!state.user) {
      return null;
    }
    return state.user;
  },
  get_menu() {
    return state.menu;
  },
  get_level() {
    return state.level;
  }
};

const mutations = {
  set_roleId(state, roleId) {
    window.sessionStorage["roleId"] = JSON.stringify("roleId");
  },
  set_token(state, token) {
    window.sessionStorage["token"] = JSON.stringify(token);
    state.token = token;
  },
  set_menu(state, menu) {
    state.menu = menu;
  },
  set_user(state, user) {
    window.sessionStorage["user"] = JSON.stringify(user);
    state.user = user;
  },
  set_level(state, level) {
    state.level = level;
  }
};
const actions = {
  set_roleId(context, r) {
    context.commit("set_roleId", r);
  },
  set_token(context, r) {
    context.commit("set_token", r);
  },
  set_menu(context, menu) {
    context.commit("set_menu", menu);
  },
  set_user(context, user) {
    context.commit("set_user", user);
  },
  set_level(context, level) {
    context.commit("set_level", level);
  }
};
const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  plugins: [vuexLocal.plugin]
});
export default store;
